/**
 * 
 */
package com.facebookdirectory.session;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.framework.PersistenceController;

import com.facebookdirectory.entity.FBAppInfo;
import com.facebookdirectory.entity.Language;

/**
 * @author piglet
 *
 */
@Scope(value = ScopeType.APPLICATION)
@Name("todaySpecialList")
public class TodaySpecialList extends AppInfoList {
	private static final long serialVersionUID = 4789719207284686073L;	
	private List<FBAppInfo> resultListEnglish;
	private List<FBAppInfo> resultListChinese;	

	private Date timeStamp;
	private static final String EJBQL_EN ="select fBAppInfo from FBAppInfo fBAppInfo where fBappInfo.category = 'Games' and fBappInfo.language=0 and fBappInfo.averageRating>0.3 and fBappInfo.monthActive>1000 order by fBAppInfo.lastUpdate desc";
	private static final String EJBQL_CH ="select fBAppInfo from FBAppInfo fBAppInfo where fBappInfo.category = 'Games' and fBappInfo.language=1 and fBappInfo.averageRating>0.3 and fBappInfo.monthActive>1000 order by fBAppInfo.lastUpdate desc";
	private Language language = Language.ENGLISH;
	
	public TodaySpecialList()
	{
		this.setEjbql(EJBQL_EN);
		setMaxResults(20);
	}
	/* (non-Javadoc)
	 * @see org.jboss.seam.framework.EntityQuery#getResultList()
	 */
	@Override
	public List<FBAppInfo> getResultList() {
		
		if(language==Language.CHINESE)
		{
			return resultListChinese;
		}
		else
		{
			updateRecommand();
			return resultListEnglish;
		}
	}

	
	/**
	 * @return the resultList
	 */
//	public List<FBAppInfo> getResultList() {
//		updateRecommand();
//		if(language==Language.CHINESE)
//		{
//			return resultListChinese;
//		}
//		else
//		{
//			return resultListEnglish;
//		}
//	}
	
	private void updateRecommand()
	{		
		Calendar now = Calendar.getInstance();		
		now.add(Calendar.DATE, 0);		
		if(resultListEnglish==null||timeStamp.before(now.getTime()))
		{			
			//fetch data from DB
		
			resultListEnglish = super.getResultList();		
//			Query query2 = getEntityManager().createQuery(EJBQL_CH);
//			query2.setMaxResults(20);
//			resultListChinese = query2.getResultList();
			//update timestamp
			timeStamp = new Date();			
		}
	}	
	
	public void changeToEnglish()
	{		
		language =  Language.ENGLISH;
	}
	
	public void changeToChinese()
	{				
		language =  Language.CHINESE;		
	}
	
}
